#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Time       :   11:01
# Author     : Y4
# desc       : 中间件
# File       : middleware.py

'''
流程
    client -> process_request[]
    逐一进行process_request[]
    process_request[] -> urls
    urls ->  process_views[]
    逐一进行process_views[]
    process_views  -> views
    views -> models
    models -> views
    views  -> response
    response -> process_response[]
    逐一进行process_response[]
'''

# ip反爬
import time

from flask import request

from App.plugins import cache


def init_middleware(app):
    @app.before_request
    def before():
        if request.path:
            ip = request.remote_addr
            black_list = cache.get('black') or []
            if ip in black_list:
                return '黑名单。。凉凉。。。'

            # 频率反爬虫 一分钟内请求10次，就被证实为小爬虫
            requests = cache.get('ip') or []
            while requests and time.time() - requests[-1] > 60:
                requests.pop()
            requests.insert(0, time.time())
            cache.set('ip', requests, timeout=60)

            if len(requests) > 30:
                black_list.append(ip)
                cache.set('black', black_list, timeout=60 * 60 * 24 * 30)  # 封一个月
                return '小爬虫小黑屋里呆着'
            if len(requests) > 10:
                return '您的访问过于频繁，小爬虫回家睡觉吧,你在访问,帐号将被限制1个月啦'
